package com.supreme.securityserver.service;

import com.supreme.commonboot.exception.BizException;
import com.supreme.commonentity.mysql.primary.SysUser;
import com.supreme.commonmybatis.service.quick.UserOrmService;
import com.supreme.securityserver.security.AuthUser;
import com.supreme.securityserver.security.AuthTokenService;
import com.supreme.securityserver.utils.SecurityUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Service
public class AuthService {

//    @Resource
//    private AuthenticationManager authenticationManager;

    @Resource
    private AuthenticationManagerBuilder authenticationManagerBuilder;

    @Resource
    private AuthTokenService authTokenService;

    @Resource
    private UserOrmService userOrmService;

    @Resource
    private RedisTemplate<String, AuthUser> redisTemplate;

    @Resource
    private HttpServletRequest httpServletRequest;

    public SysUser userRegister(String username, String password) {
        SysUser sysUser = userOrmService.getUserByUsername(username);
        if (Objects.nonNull(sysUser)) {
            throw new BizException("用户已存在");
        }

        String encryptPassword = SecurityUtils.encryptPassword(password);
        String userCode = RandomStringUtils.randomNumeric(8);
        sysUser = new SysUser()
                .setUsername(username)
                .setPassword(encryptPassword)
                .setUserCode(userCode)
                .setGender("male");
        boolean result = userOrmService.save(sysUser);
        if (!result) {
            throw new BizException("用户创建失败");
        }

        return sysUser;
    }

    public String userLogin(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);

        AuthUser authUser = (AuthUser) authentication.getPrincipal();
        return authTokenService.generateToken(authUser);
    }
}
